package q43

import (
	"strconv"
	"strings"
)

func multiply(num1 string, num2 string) string {
	var s string
	if len(num1) <= 1 && len(num2) <= 1 {
		n1, _ := strconv.Atoi(num1)
		n2, _ := strconv.Atoi(num2)
		return strconv.Itoa(n1 * n2)
	} else if len(num1) < 1 || len(num2) < 1 {
		return "0"
	}

	a := num1[:len(num1)-1]
	b := num1[len(num1)-1:]

	c := num2[:len(num2)-1]
	d := num2[len(num2)-1:]

	//log.Println(a,b,c,d);
	//return "";

	s1 := plus(e(multiply(a, c), 2), e(multiply(a, d), 1))
	s2 := plus(e(multiply(b, c), 1), multiply(b, d))
	s = plus(s1, s2)

	return s
}

func e(num string, e int) string {
	if num == "0" {
		return "0"
	}
	if e <= 0 {
		return num
	}
	return num + strings.Repeat("0", e)
}

//相加
func plus(num1 string, num2 string) string {

	numArr1 := strings.Split(num1, "")
	numArr2 := strings.Split(num2, "")
	l1 := len(numArr1)
	l2 := len(numArr2)
	//保证 l1小l2大
	if l1 > l2 {
		numArr1, numArr2 = numArr2, numArr1
		l1, l2 = l2, l1
	}

	var carry int = 0
	var s string
	for i := 0; i < l2; i++ {
		if i >= l1 && carry <= 0 {
			s = strings.Join(numArr2[:l2-i], "") + s
			break
		}

		var n1 int
		var n2 int
		n2, _ = strconv.Atoi(numArr2[l2-i-1])
		if i > l1-1 {
			n1 = 0
		} else {
			n1, _ = strconv.Atoi(numArr1[l1-i-1])
		}

		sum := n1 + n2 + carry
		carry = sum / 10
		r := sum % 10
		s = strconv.Itoa(r) + s
		//log.Printf("%s,%d,%d\n",s,r,carry);

	}
	if carry > 0 {
		s = strconv.Itoa(carry) + s
	}

	return s
}
